//
//  SSEmoticonBottomView.swift
//  SSSina
//
//  Created by ss on 2017/7/10.
//  Copyright © 2017年 ss. All rights reserved.
//

import UIKit
//  UIStackView -> iOS 9.0 以后出现的(容器视图)
// 按钮枚举
enum SSEmoticonBottomViewType: Int{
    case recent = 2001
    case normal
    case emoji
    case lxh
}
class SSEmoticonBottomView: UIStackView {
    
    // 声明一个闭包
    var closure:((SSEmoticonBottomViewType)->())?
    
    // 记录选中的按钮
    var currentButton: UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 设置视图
    private func setupUI(){
        // 设置布局方式
        axis = .horizontal
        // 填充方式
        distribution = .fillEqually
        
        addChildButton(title: "最近", imgName: "left", type: .recent)
        addChildButton(title: "默认", imgName: "mid", type: .normal)
        addChildButton(title: "Emoji", imgName: "mid", type: .emoji)
        addChildButton(title: "浪小花", imgName: "right", type: .lxh)
    }
    
}

extension SSEmoticonBottomView{
    // 创建按钮的公共方法
    fileprivate func addChildButton(title: String, imgName: String, type: SSEmoticonBottomViewType){
        let button = UIButton()
        button.tag = type.rawValue
        // 默认请求下 默认按钮为选中状态
        if type == .normal {
            button.isSelected = true
            // 设置选中按钮
            currentButton = button
        }
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.setTitle(title, for: UIControlState.normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: SSNormalFontSize)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.selected)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_normal"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_selected"), for: UIControlState.selected)
        // 添加按钮
        addArrangedSubview(button)
    }
    // 监听事件
    // 01 把上个按钮变为正常 02 把点击的按钮设置为选中
    @objc fileprivate func buttonClick(button: UIButton){
        // 判断当前点击的按钮是否和currentbutton一样
        if currentButton == button {
            return
        }
        currentButton?.isSelected = false
        button.isSelected = true
        currentButton = button
        closure?(SSEmoticonBottomViewType(rawValue: button.tag)!)
    }
}

